import React from 'react'
// ===================================================================== Temp
import Controls from '#cpt/temp/Controls'
import TableControls from '#cpt/temp/TableControls'
import Table from '#cpt/temp/Table'
import SubmitForm from '#cpt/temp/SubmitForm'
import Confirm from '#cpt/temp/Confirm'
import Cols from '#private/cols'
// ===================================================================== global declare
const { $fn, $http, $Lazy } = window
// ===================================================================== private component
const Page 			= $Lazy.load(()=>import('#tp/page/page-container-scroll'))
const Select 		= $Lazy.load(()=>import('@antd/form/select'))
const Box 			= $Lazy.load(()=>import('#tp/box/box'))
const $cache 		= $Lazy.file(()=>import('#private/cache-api'))
const message 		= $Lazy.file(()=>import('@antd/message'))
// 
const Batch 		= $Lazy.state(()=>import('./cpt/batch-modal'))
const Upload 		= $Lazy.state(()=>import('./cpt/upload-modal'))

class Index extends React.Component{
	state = {
		data:[],
		// 搜索表单列表
		formData : [
			{ label: '医院名称录入',	name: '',								half:true,				type: 'checkbox',	onValue: ({value, formData}) => {
				if (value) {
					formData[1].hide = true
					formData[2].hide = true
					formData[3].hide = false
					formData[4].hide = false
				} else {
					formData[1].hide = false
					formData[2].hide = false
					formData[3].hide = true
					formData[4].hide = true
				}
				this.setState({ formData })
				this.formRef.setValue({hosp_code: '', hosp_id: '', hosp_name: ''})
		} },

			// 一组
			{ label: '医院条码',			name: 'hosp_code',			half:true,			required:true,
				onEnter: value => {
					const { formData } = this.state
					const arr = formData[3].data.filter(v => v.hosp_spec === value )
					const hosp_name = $fn.hasArray(arr) ? arr[0].name : '无'
					this.formRef.setValue({ hosp_name })
				},
				onValue: ({value}) => {
					const { formData } = this.state
					const arr = formData[3].data.filter(v => v.hosp_spec === value )
					const hosp_name = $fn.hasArray(arr) ? arr[0].name : '无'
					this.formRef.setValue({ hosp_name })
				}
			},
			{ label: '医院名称',			name: 'hosp_name',			half:true,			readOnly:true,			p:'请先输入医院条码'	 },
			
			// 二组
			{ label: '医院名称',			name: 'hosp_id',			half:true,			hide: true,				type:'select',		required:true,	copy:true,		
				onValue: ({rows}) => {
					if(rows){
						this.formRef.setValue({ hosp_code: rows.hosp_spec})
					}
				}
			},
			{ label: '医院条码',			name: 'hosp_code',			half:true,			hide: true,									readOnly:true,		p:'请先选择医院名称', 	 },
			

			{ label: '标本数量',			name: 'spec_num', 			half:true,				value: '1', 			},
			{ label: '标本性状',			name: 'spec_traits',		half:true,				type: 'select',							loading:true,			idStr: 'code', value: '21002',	 },
			{ label: '标箱条码',			name: 'box_code',			half:true,				required:true ,							},
			{ label: '识别标签',			name: 'tag',				full:true,				type: 'checkboxGroup',			idStr: 'code',  	},
			{ label: '加做项目',			name: 'additional_kind',	width:'30%',			type: 'checkbox',	value:0 },
			{ label: '复查',				name: 'is_review',			width:'30%',			type: 'checkbox', 	value:0 },
			{ label: '批量',				name: 'isBatch',			width:'30%',			type: 'checkbox', 					
				onValue: ({value, formData}) => {
					if (value) {
						this.setState({isBatch: true})
						$fn.getRow(formData, 'end_code').disabled = false
					} else {
						this.setState({isBatch: false})
						$fn.getRow(formData, 'end_code').disabled = true
					}
					this.setState({formData})
				}
			},
			{ label: '快速录入',			name: 'isQuickEntry',		width:'30%',		type: 'checkbox', 				 },
			{ label: '记忆项目',			name: 'isMemoProject',		width:'30%',		type: 'checkbox',					
				onValue: ({value, formData}) => {
					const { data } = this.state
					// 将值写入 kind_ids
					if (value) {
						let d = data.map(i => i.kind_id)
						formData.kind_ids = d
					} else {
						formData.kind_ids = []
					}
					this.setState({formData, data: []})
				}
			},
			{ label: '开始条码号',		name: 'start_code',  		half:true,					max:12, 	
				onValue: ({value, formData}) => {
					// 输入 12位 启用 生成按钮
					if (value.length === 12) {
						$fn.getRow(formData, 'end_code').btn.disabled = false
						this.state.isBatch && document.querySelector('.end_code .ant-input.ant-input-borderless').focus()
					} else {
						$fn.getRow(formData, 'end_code').btn.disabled = true
					}
					this.setState({formData})
				},
				onEnter: val => this.getHospital()
			},
			{ label: '结束条码号',		name: 'end_code',	 		disabled: true,		half:true,				max:12,				itemClassName: 'end_code',
				btn: { label: '生成', 	disabled: true,	onClick: value=>{ this.generateCode() } },
				onEnter: val => this.getHospital()
			},
			// 快捷录入不连接多条码录入项目 2021/9/27 --马婷
			{ label: '条码号', 		name:'spec_codes', 	full:true, 	type:'textarea',	required:true,
				btn: { label: '确认',
					onClick: value=>{
						const { formData } = this.state
						// 获取表单的值
						let form = this.formRef.getName()
						let {spec_codes} = form
						if(spec_codes){
							spec_codes = spec_codes.match(/\d{14}|\d{12}/g)
							spec_codes = Array.from(new Set(spec_codes))
							spec_codes.sort()
						}
						if(spec_codes.length > 1){
							this.formRef.setValue({isBatch:1})
							this.setState({isBatch:1})
						}
						// 格式化参数
						let param = {
							start_code: form.start_code || '',
						 	end_code: form.end_code || '',
							spec_codes: spec_codes || '',
							spec_traits: form.spec_traits || '21002',
							hosp_code: form.hosp_code || '',
							box_code: form.box_code || '',
							spec_num: form.spec_num || 1,
							critical: 0,
							tag: form.tag,
							checked: form.isBatch // 是否批量
						};

						// 保存条码
						$http.submit(null,'specimen/add',{ param }).then(data=>{
							// 将uuid添加到modal
							this.modal.audit_status =  data[0].audit_status
							this.modal.uuid =  data[0].uuid
							this.modal.spec_code =  data[0].spec_code

							// 启用项目选择按钮
							$fn.disabledRows(formData, 'project_id', false)

							// 将数据传入上传图片控件
							this.uploadRef.setState({data: data})

							// 勾选记忆项目
							if (form.isMemoProject) {
								const { kind_ids } = this.state
								if (kind_ids.length) {
									let d = {
										kind_ids: kind_ids,
										spec_id: data[0].uuid,
										spec_code: data[0].spec_code
									}
									// 添加项目
									this.addProjectds(d, true)
								}
							}

							// 勾选批量
							const {isBatch} = this.formRef.getName()
							if (isBatch) {
								let param = {
									start_code: form.start_code,
									end_code: form.end_code,
									spec_codes:spec_codes
								}
								// 写入批量条码表格的数据
								$http.submit(null, 'specimen/checkenter', { param }).then(data => {
									// 将数据写入子表格
									this.batchRef.setState({data: data.res})
									this.setState({ batchCode: data.res })
								})
							}

							// 刷新状态
							this.setState({formData})
						})
					}
				}
			},
			{ label: '选择项目',			name: 'project_id',  		full: true,			type: 'select-table',	cols:Cols['specimenkindSelect'],		loading:true,		  disabled: true,
				onValue: ({value}) => {
					if (value) {
						// 获取表单的值
						// let form = this.formRef.getName()
						const d = {
							spec_id: this.modal.uuid,
							// spec_code取specimen/add接口返回的第一个数
							// spec_code: form.start_code,
							spec_code:this.modal.spec_code,
							kind_ids: [value]
						}
						// 添加项目
						this.addProjectds(d, false)
					}
				}
			},
			{ label: '备注',					name: 'remark',										full: true,				type: 'textarea' },
			{ label: '医院特殊要求',			name: 'project_special_request',					full: true,				type: 'textarea',	disabled: true },
		],
		// 是否批量 控制显示 批量条码的表格
		isBatch: false,
		// 记忆项目
		kind_ids: [],
		// 项目明细
		details: [],
		// 标本类型
		spec_type: [],
		// 批量条码的数据
		batchCode: []
	}
	
	modal = { add: '', audit_status: null }
	
	query = {}
	
	componentDidMount(){
		this.getSelect()
		this.setState({formData: this.state.formData})
	}
	
	// 回车自动带出医院 2021-9-26 4:10:29 ?F10: PM? --伍智睿
	getHospital = () => {
		const { start_code, end_code } = this.formRef.getValue()
		$http.submit(null,'/barcode/checkCodeEnter', { param:{start_code, end_code} }).then(({hosp_name, hosp_spec, uuid}) => {
			this.formRef.setValue({ hosp_name: hosp_name, hosp_code: hosp_spec, hosp_id: uuid })
		})
	}
	// 生成条码
	generateCode(){
		const {start_code, end_code} = this.formRef.getValue(['start_code','end_code'])
		if(start_code && (start_code.length === 12 || start_code.length === 14) ){
			if(start_code && end_code && +start_code > +end_code ){
				return $fn.msg.warning('开始条码必须小于结束条码')
			}else{
				let arr =[]
				if(end_code && (end_code.length === 12 || end_code.length === 14)){
					for(var i = parseInt(start_code); i <= parseInt(end_code); i++){
						arr.push(i)
					}
				}else if(start_code && !end_code){
					arr = [start_code]
				}
				let {spec_codes} = this.formRef.getValue(['spec_codes'])
				if(spec_codes){spec_codes = spec_codes.match(/\d{14}|\d{12}/g)}
				let specData = []
				if(spec_codes){
					spec_codes.forEach(v=>{
						specData.push(parseInt(v))
					})
				}
				spec_codes = Array.from(new Set([...specData, ...arr]))
				this.formRef.setValue({spec_codes: spec_codes.join('\r')})
			}
		}else{
			return $fn.msg.warning('开始条码不正确')
		}
	}
	
	// 查询条码信息
	querySpecId() {
		const form  = this.formRef.getName()
		let {spec_codes} = form
		if(spec_codes){
			spec_codes = spec_codes.match(/\d{14}|\d{12}/g)
			spec_codes = Array.from(new Set(spec_codes))
			spec_codes.sort()
		}
		$http.submit(null, 'specimen/getspeccodeInfo', { param: { spec_code: spec_codes[0], additional_kind: form.additional_kind ? 1 : 0 } }).then(data => {
			// 处理表单数据
			this.formRef.setValue({ tag: [], start_code: form.spec_code })
			let d = {
				spec_id: this.modal.uuid,
				spec_code: data.spec_code
			}
			if (form.isMemoProject) {
				// 添加项目
				this.addProjectds(d, true);
			} else {
				// 获取项目
				this.getProjectds(d, false);
			}

		}).catch(data => {
			this.getProjectds()
		})
	}

	// 处理 批量条码 的数据
	getSpec_ids() {
		const { data } = this.state
		let spec_ids = []
		if (data.length) data.map(item => spec_ids.push(item.uuid))
		return spec_ids
	}

	// 获取项目
	getProjectds = (data) => {
		if (data) {
			let param = {
				...data
			}
			$http.submit(null, 'specimen-kind/index', { param }).then(data => {
				// 写入项目明细表格数据 和 表单数据
				this.setState({ data })
			})
		} else {
			// 设置项目明细表格数据设为空
			this.setState({ data: [] })
		}
	}

	// 添加项目
	addProjectds = (param, isMemoProject) => {
		const { kind_ids } = this.state
		$http.submit(null, 'specimen-kind/batchadd', { param }).then(() => {
			let d = {
				spec_id: param.spec_id,
				spec_code: param.spec_code
			}
			// 勾选记忆项目
			if (!isMemoProject) {
				kind_ids.push(...param.kind_ids)
				this.setState({kind_ids})
			}
			this.getProjectds(d)
			// 清空 选择项目
			this.formRef.reset(['project_id'])
		}).catch(() => {
			// 清空 选择项目
			this.formRef.reset(['project_id'])
		})
	}

	// 提交表单信息
	submitInfo(form) {
		let params = {}
		if (this.modal.uuid) {
			params	= {
				spec_id: this.modal.uuid,
				is_review: form.is_review,
				additional_kind: form.additional_kind,
				remark: form.remark
			}
		}
		let param
		// 提取批量条码的数据
		if (form.isBatch) {
			let to_codes = []
			this.state.batchCode.forEach(i => {
				to_codes.push(i.spec_code)
			})
			param = {
				to_codes: to_codes,
				...params
			}
		} else {
			param = {
				...params
			}
		}
		$http.submit(null, 'specimen-kind/savekind', { param }).then(data => {
			this.formatForm()
			// 清空上传 条码 和 图片
			this.uploadRef.setState({data: data, img: ''})
		})
		window.onRefresh = () => {		 /*  添加异步 2021-8-24 --马婷 */
			this.formatForm()
			// 清空上传 条码 和 图片
			this.uploadRef.setState({data: [], img: ''})
		}
	}

	// 格式化表单
	formatForm() {
		let form = this.formRef.getName()
		const { formData, isBatch } = this.state
		// 选择项目框 禁用
		$fn.disabledRows(formData, 'project_id', true)
		// 将批量条码的表格清空
		if (isBatch) {
			this.batchRef.setState({ data: [] })
		}
		// 是否快速录入
		if(form.isQuickEntry) {
			this.formRef.setValue({start_code: '', end_code: '', project_id: '', spec_codes:''})
			// 开始条码获取焦点
			this.inputFoucus(3)
			if (!form.isMemoProject) {
				this.setState({ data: [] })
			}
			return
		}
		// 记忆项目
		if (form.isMemoProject) {
			this.formDataInit()
			// 开始条码获取焦点
			this.inputFoucus(3)
			return
		}
		this.formDataInit()
		// 开始条码获取焦点
		this.inputFoucus(3)
		this.setState({ data: [] })
	}
	
	// 输入框获取焦点 
	inputFoucus(val) {
		setTimeout(() => {
			document.querySelectorAll('.ant-input.ant-input-borderless')[val].focus()
		}, 500)
	}
	
	// 初始化 formData 表单
	formDataInit() {
		// 设置表单 默认值
		this.formRef.setValue({
			spec_num: '1', 								// 标本数量
			spec_traits: '21002',					// 标本性状
		})
		// 清理 表单
		this.formRef.reset(['box_code', 'hosp_code', 'hosp_id', 'critical', 'is_review', 'additional_kind', 'start_code', 'end_code', 'tag', 'remark', 'project_special_request', 'project_id','spec_codes'])
		this.modal.add = ''
	}

	// 获取下拉数据
	getSelect = () => {
		const { formData } = this.state
		
		$cache.then( async f => {

			// 识别标签 和 标本性状
			const dic = await f.getDicCache({ code: [21000, 69700, 2000] })

			//识别标签
			$fn.setRow( formData, 'tag', dic['69700'] )
			// 标本性状
			$fn.setRow( formData, 'spec_traits', dic['21000'] )
			// 医院名称
			$fn.setRow( formData, 'hosp_id', await f.getCache({ api:'bs-hospital/select' }) )
			// 选择项目
			$fn.setRow( formData, 'project_id', await f.getCache({ api:'specimenkindSelect' }) )
			
			this.setState({ formData, spec_type: dic['2000'] })
		})
	}

	// 表格
	cols = [
		{ title: '项目代码',  dataIndex: 'kind_code',       ...$fn.table.spec_code },
		{ title: '项目名称',  dataIndex: 'kind_name' },
		{ title: '项目属性',  dataIndex: 'kind_type_name' },
		{ title: '项目类别',  dataIndex: 'category_name' },
		{ title: '子项目',    dataIndex: 'child_kind_name' },
		{ title: '岗位',      dataIndex: 'project_name' },
		{ title: '项目状态', 	dataIndex: 'child_kind_name',
      render: text => {
        let value
        if (text === '1') {
          value = '已审核'
        } else if (text === '0') {
          value = '待审核'
        } else {
          value = '待保存'
        }
        return value
      },
      ...$fn.table.status
    },
		{ title: '标本类型', 	dataIndex: 'spec_type',
      render: (text, rows) => <Select size='small' bordered p='请选择' value={text} data={this.state.spec_type} idStr='code'
        onChange={ value => {
          let param = {
            spec_type: value,
            uuid: rows.uuid
          }
          $http.submit(null, 'specimen-kind/savespectype', { param }).then(data => {
            this.querySpecId()
          })
        } }
      />
    },
    TableControls.controls.call(this,{ width: 100 })
	]
	
	// 页头按钮
	controls = () => {
		return [
			Controls.click.call(this, '保存',  
			()=>{
				const { isBatch  } = this.state
				let form = this.formRef.getName()
				if (isBatch) {
					// startNum 和 endNum 用于判断填入条码号 是否是 同一公司的
					// let startNum = form.start_code.substr(0, 2)
					// let endNum = form.start_code.substr(0, 2)
					// if (!form.start_code || !form.end_code) {
					// 	message.then(f=>f.error('请输入开始条码或结束条码', 1))
					// 	return
					// }
					// if (startNum !== endNum) {
					// 	message.then(f=>f.error('请输入同一个分公司的开始条码和结束条码', 1))
					// 	return
					// }
					// if (form.end_code - form.start_code <= 0) {
					// 	message.then(f=>f.error('结束条码必须大于开始条码', 1))
					// 	return
					// }
					this.submitInfo(form)
				} else {
					this.submitInfo(form)
				}
			},
			{ code: 'F2' }),
			Controls.click.call(this, '保存并审核', ()=>{
				let form = this.formRef.getName()
				const param = {
					...form,
					status: '1',
					spec_id: this.modal.uuid,
					// spec_code: this.start_code,
					spec_code: this.modal.spec_code,
					audit_status: this.modal.audit_status,
					is_review: form.is_review,
					additional_kind: form.additional_kind,
					remark: form.remark,
					uuid: this.modal.uuid,
				}
				if (form.isBatch) {
					let to_codes = []
					this.state.batchCode.forEach(i => {
						to_codes.push(i.spec_code)
					})
					param.to_codes = to_codes
				}
				$http.submit(null, 'specimen/saveandaudit', { param }).then(data => {
					// 清空上传 条码 和 图片
					this.uploadRef.setState({data: data, img: ''})
					this.formDataInit()
					message.then(f=>f.success('保存并审核成功'))
					if (!form.isMemoProject){
						this.setState({data:[],kind_ids:[]})
					}
					if(this.state.isBatch){
						this.batchRef.setState({data: []})
						this.setState({ batchCode: []})
					}
				})
				window.onRefresh = () => {		 /*  添加异步 2021-8-24 --马婷 */
					// 清空上传 条码 和 图片
					this.uploadRef.setState({data: [], img: ''})
					this.formDataInit()
					if (!form.isMemoProject){
						this.setState({data:[],kind_ids:[]})
					}
					if(this.state.isBatch){
						this.batchRef.setState({data: []})
						this.setState({ batchCode: []})
					}
				}
			},
			{ code: 'F4' }),
		]
	}

	// 表格按钮
	table_controls = (text, val) => {
		return [
			Confirm.call(this, '删除', 'specimen-kind/del', { submit: { to_spec_ids: this.getSpec_ids(), kind_id: val.uuid, spec_id: [val.spec_id] },
        onOk: () => {
          let d = this.state.data.filter(item => item.uuid !== val.uuid)
          this.setState({data: d})
        }
      })
		]
	}
	
	onSubmit = () =>  this.formRef.submit()
	
	render(){
		const { isBatch } = this.state
		
		return (
			<Page  title='快速录入项目' controls={ this.controls() }>
				{/* Form */}
				<div className='fx bcf pt10 pr10' style={{ height:700 }}>
					<div style={{width:'50%'}}>
						{SubmitForm.call(this, { labelWidth:'s8' })}
					</div>
					<Upload onRef={ref=>this.uploadRef=ref} />
				</div>
				{/* 批量条码表格 */}
				{
					isBatch && <Batch onRef={ref=>this.batchRef=ref} />
				}
				{/* 表格 */}
				<Box title="项目明细" style={{ height: 400 }} flex contentClassName='rel fv pt10 p'>
					{ Table.call(this, { wrapClassName: 'xmlr' }) }
				</Box>
			</Page>
		)
	}
}

export default Index